package com.Netty.heart.client;

import com.Netty.heart.comment.CustomHeartbeatHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

/**
 * Created by thinkjoy on 2017/6/29.
 */
public class ClientHnadler extends CustomHeartbeatHandler {

    private Client client;

    public ClientHnadler(Client client) {
        super("client");
        this.client = client;
    }

    /**
     * 收到服务端传来的消息并显示
     * @param channelHandlerContext
     * @param byteBuf
     */
    @Override
    protected void handleData(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) {
        byte[] data=new byte[byteBuf.readableBytes()-5];
        byteBuf.skipBytes(5);
        byteBuf.readBytes(data);
        String content = new String(data);
        System.out.println(name + " get content: " + content);
    }

    /**
     * 读写超时，向服务端发起ping心跳检测
     * @param ctx
     */
    @Override
    protected void handleAllIdle(ChannelHandlerContext ctx) {
        super.handleAllIdle(ctx);
        sendPingMsg(ctx);
    }

    /**
     * 当掉线后，重新连接
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        client.doConnect();
    }
}
